package com.wyait.manage.web.work;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.wyait.manage.entity.Internship;
import com.wyait.manage.entity.Work;
import com.wyait.manage.pojo.User;
import com.wyait.manage.service.InternshipService;
import com.wyait.manage.service.WorkService;
import com.wyait.manage.service.impl.WorkComputeService;
import com.wyait.manage.utils.ExcelServiceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("data")
@Slf4j
public class DataController {

    @Autowired
    private ExcelServiceUtil excelServiceUtil;

    private Pattern r = Pattern.compile("\\[(\\d*)\\](\\S*)");

    @Resource
    private WorkService workService;

    @Autowired
    WorkComputeService workComputeService;

    @Autowired
    InternshipService internshipService;


    @PostMapping("/import/class")
    public void importClassTable(@RequestParam String filePath) {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(3);
        importParams.setHeadRows(1);

        List<Work> works = excelServiceUtil.getEntitysFromExcel(importParams, Work.class, filePath);
        for (Work work : works) {
            String[] workId = getWorkId(work.getTeacherName());
            work.setTeacherName(workId[1]);
            work.setWorkId(workId[0]);

            workService.insert(work);
        }
    }

    @PostMapping("/import/internship")
    public void importInternShipTable(@RequestParam String filePath) {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(3);
        importParams.setHeadRows(1);

        List<Internship> internships = excelServiceUtil.getEntitysFromExcel(importParams, Internship.class, filePath);
        for (Internship internship : internships) {

            String instructor = internship.getInstructor();
            String[] split = instructor.split("；");
            if (split.length >= 2) {

                String[] workId = getWorkId(split[0]);
                internship.setWorkId(workId[0]);
                internship.setInstructor(workId[1]);

                internshipService.update(internship);
                for (int i = 1; i < split.length; i++) {
                    internship.setId(null);
                    workId = getWorkId(split[i]);
                    internship.setWorkId(workId[0]);
                    internship.setInstructor(workId[1]);

                    internshipService.insert(internship);
                }
            } else {

                String[] workId = getWorkId(split[0]);
                internship.setWorkId(workId[0]);
                internship.setInstructor(workId[1]);

                internshipService.update(internship);
            }
        }
    }


    @GetMapping("/compute")
    public void compute() {
        workComputeService.compute();
    }


    @RequestMapping(value = "/export",consumes = "application/json;charset=utf-8")
    public void export (HttpServletResponse response){
        //@RequestBody User user,
        OutputStream out = null;
        String name = "工作量";

        List<Work> all = null;
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if("".equals(user.getWorkId()) || user.getWorkId() == null){
            all = workService.getAll();
        } else {
            all = workService.queryByWorkId(user.getWorkId());
        }
        System.out.println(all.size());
        try {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(name, "UTF-8")+".xlsx");
            out = response.getOutputStream();
            ExportParams params = new ExportParams();
            params.setTitle("工作量");
            params.setType(ExcelType.XSSF);
            Workbook sheets = ExcelExportUtil.exportExcel(params, Work.class, all);
            sheets.getSheetAt(0).getFooter().setCenter("签字：");

            sheets.write(out);
            out.flush();
            out.close();
            log.info("学生信息表导出成功");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{

        }
    }

    /**
     * 通过正则表达式获取教师工号以及教师名称
     * @param excelValue
     * @return
     */
    private String[] getWorkId(String excelValue){
        Matcher matcher = r.matcher(excelValue);

        while(matcher.matches()){
            return new String[]{matcher.group(1),matcher.group(2)};
        }
        return null;
    }

}
